package com.mopa.qzone;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;

import com.mopa.shareAlll.ShareAllActivity;
import com.tencent.tauth.TencentOpenAPI;
import com.tencent.tauth.http.Callback;
import com.tencent.tauth.http.TDebug;
public class UploadPicClickListener implements OnClickListener {
	private ShareAllActivity mActivity;
	public UploadPicClickListener(ShareAllActivity activity) {
		mActivity = activity;
	}
	@Override
	public void onClick(View v) {
		if (!mActivity.satisfyConditions()) {
			TDebug.msg("请先获取access token和open id", mActivity);
			return;
		}
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
		intent.addCategory(Intent.CATEGORY_OPENABLE);
		intent.setType("image/*");
		mActivity.startActivityForResult(intent, ShareAllActivity.REQUEST_PICK_PICTURE);
		
	}
	public static void uploadPic(final ShareAllActivity activity, Uri uri) {
		activity.showDialog(ShareAllActivity.PROGRESS);
		Bundle bundle = null;
		bundle = new Bundle();
		byte[] buff = null;
		try {
			InputStream is = activity.getContentResolver().openInputStream(uri);
			ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int len = 0;
			while( (len = is.read(buffer)) !=-1 ){
				outSteam.write(buffer, 0, len);
			}
			outSteam.close();
			is.close();
			buff = outSteam.toByteArray();
		} catch (IOException e) {
			e.printStackTrace();
		}
		bundle.putByteArray("picture", buff);//
		bundle.putString("photodesc", "@MMopa" + new Date()); 
		bundle.putString("title", "mopa_" + System.currentTimeMillis() + ".png");//
		bundle.putString("x", "0-360");
		bundle.putString("y", "0-360");
		TencentOpenAPI.uploadPic(activity.mAccessToken, activity.mAppid, activity.mOpenId, bundle, new Callback() {
			
			@Override
			public void onSuccess(final Object obj) {
				activity.runOnUiThread(new Runnable() {
					
					@Override
					public void run() {
						activity.dismissDialog(ShareAllActivity.PROGRESS);
						activity.showMessage("用户上传照片返回数据", obj.toString());
					}
				});
			}
			
			@Override
			public void onFail(final int ret, final String msg) {
				activity.runOnUiThread(new Runnable() {
					@Override
					public void run() {
						activity.dismissDialog(ShareAllActivity.PROGRESS);
						TDebug.msg(ret + ": " + msg, activity);
					}
				});
			}
		});
	}

}
